import React, { ReactChild, useContext, useMemo } from 'react';
import cls from 'classnames';
import { InbizIcon } from '@inbiz/utils';
import { InBizTableCtx } from '../../context';
import { useInbizPrefixCls, useIsDesigner } from '../../hooks';
import { DroppableWidget } from '@inbiz/react';
import { isArray } from 'lodash';

const TableTopBtnGroup = (props: { children: ReactChild }) => {
  const { showPageType, buttonPosition, thumbnail, changeView,viewMode } = useContext(InBizTableCtx);
  const isDesignable = useIsDesigner();
  const btnGroupViewRight = useInbizPrefixCls('table-btn-group-right');
  const btnGroup = useInbizPrefixCls('table-btn-group');
  const children = useMemo(() => {
    const btns = props.children?.props?.children[0] || [];
    if (isArray(btns)) {
      btns.forEach((btn: any, index: number) => {
        const componentProps = btn.props.node.props || {};
        if (
          componentProps['x-component'] == 'EformButtonGroup' ||
          componentProps['x-component'] == 'EformButton'
        ) {
          props.children.props.children[0][index].props.node.props['x-decorator-props'].style = {
            height: '32px',
            margin: index != 0 ? '0px 0px 0px 10px' : '0',
            width: 'auto',
            ...componentProps['x-decorator-props'].style,
          };
        }
      });
    } else {
      const componentProps = btns?.props?.node?.props || {};
      if (
        componentProps['x-component'] == 'EformButtonGroup' ||
        componentProps['x-component'] == 'EformButton'
      ) {
        props.children.props.children[0].props.node.props['x-decorator-props'].style = {
          height: '32px',
          width: 'auto',
          ...componentProps['x-decorator-props'].style,
        };
      }
    }
    return props.children;
  }, [props.children]);


  return isDesignable ? (
    <div {...props}>
      <DroppableWidget style={{ flex: 1 }}>
        <div className="inbiz-table-btn-group">{children}</div>
      </DroppableWidget>
      {thumbnail && (
        <span className="inbiz-table-switch-view">
          <InbizIcon type="icon-ic-suolvetu1" style={{ fontSize: 32 }} />
        </span>
      )}
    </div>
  ) : (
    <div className="inbiz-table-btn-group-box">
      <div
        className={buttonPosition == 'right' ? cls([btnGroup, btnGroupViewRight]) : cls(btnGroup)}
      >
        {viewMode=='look'?'':props.children}
      </div>
      {thumbnail && (
        <span className="inbiz-table-switch-view" onClick={changeView}>
          {showPageType == 'list' ? (
            <InbizIcon type="icon-ic-suolvetu1" style={{ fontSize: 32, color: '#666' }} />
          ) : (
            <InbizIcon type="icon-ic-liebiao1" style={{ fontSize: 32, color: '#666' }} />
          )}
        </span>
      )}
    </div>
  );
};

export default TableTopBtnGroup;
